package com.situ.mall.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mysql.jdbc.log.Log;
import com.situ.mall.entity.Order;
import com.situ.mall.entity.OrderItem;
import com.situ.mall.mapper.CartMapper;
import com.situ.mall.mapper.OrderItemMapper;
import com.situ.mall.mapper.OrderMapper;
import com.situ.mall.service.IOrderService;
import com.situ.mall.util.DateUtil;
import com.situ.mall.vo.CartVO;

@Service
public class OrderServiceImpl implements IOrderService{
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private OrderItemMapper orderItemMapper;

	@Override
	public void insert(Order order) {
		// 现在这个order里面已经有userId,shippingId,paymentType
		// orderNo使用当前的日期和时间 202103291047123
		Long orderNo = DateUtil.getCurrentTime();
		order.setOrderNo(orderNo);
		// statusint(10)订单状态:0-已取消-10-未付款，20-已付款，40-已发货，50-交易成功，60-交易关闭
		order.setStatus(10);
		
		// 查询cart表里面属于这个用户而且checked是1的所有购物车
		List<CartVO> list = cartMapper.selectByUserIdAndChecked(order.getUserId());
		BigDecimal payment = BigDecimal.valueOf(0.0);// 计算订单总价格
		for (CartVO cartVO : list) {
			OrderItem orderItem = new OrderItem();
			orderItem.setOrderNo(orderNo);
			orderItem.setUserId(order.getUserId());
			orderItem.setProductId(cartVO.getProductId());
			orderItem.setProductName(cartVO.getProductName());
			orderItem.setProductImage(cartVO.getProductMainImage());
			orderItem.setCurrentUnitPrice(cartVO.getProductPrice());
			orderItem.setQuantity(cartVO.getQuantity());
			
			// 计算OrderItem里面商品价格*数量
			BigDecimal quantity = BigDecimal.valueOf(cartVO.getQuantity());
			BigDecimal cartItemTotalPrice = cartVO.getProductPrice().multiply(quantity);
			orderItem.setTotalPrice(cartItemTotalPrice);
			
			// 每遍历一个OrderItem加到payment上
			payment = payment.add(cartItemTotalPrice);
			
			orderItemMapper.insert(orderItem);
		}
		
		order.setPayment(payment);
		orderMapper.insert(order);
	}

}